package com.hiof.media;

import android.os.*;
import com.hiof.Configuration;
import com.hiof.servercommunication.background.job.JobThreadQueue;
import com.hiof.servercommunication.background.job.MediaSendJob;
import com.hiof.servercommunication.push.beans.MediaSendPacket;
import com.hiof.utility.Utility;

/**
 * Created with IntelliJ IDEA.
 * User: manish
 * Date: 4/16/12
 * Time: 2:32 PM
 * To change this template use File | Settings | File Templates.
 */
public class MediaFilesObserver extends FileObserver {
    private static MediaFilesObserver instance;

    public static MediaFilesObserver getInstance() {
        if (null == instance) {
            instance = new MediaFilesObserver();
        }
        return instance;
    }

    public void destroy() {
        if (instance != null)
            instance = null;
    }

    private MediaFilesObserver() {
        super(Configuration.IMAGE_FILE_URL, FileObserver.CREATE);
        Utility.debug("File Path", Configuration.IMAGE_FILE_URL);
    }

    @Override
    public void onEvent(int event, String path) {
        Utility.debug("Inside Event", path);
        try {
            if (path != null && path != "") {

                if (!path.equals(".probe")) {
                    String imagePath = Configuration.IMAGE_FILE_URL + "/" + path;
                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    msg.setData(bundle);
                    bundle.putString("imagePath", imagePath);
                    imageSavedHandler.sendMessage(msg);
                }
            }
        } catch (Exception e) {
            Utility.error(this.getClass().toString(), "Exception:" + e.getMessage());
        }
    }

    Handler imageSavedHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.getData().get("imagePath") != null) {
                String imagePath = msg.getData().get("imagePath").toString();
                Utility.debug(this.getClass().toString(), "File: " + imagePath + " uploading");
                MediaSendPacket mediaPacket = new MediaSendPacket(imagePath);
                JobThreadQueue queue = JobThreadQueue.getInstance();
                MediaSendJob mediaSendJob = new MediaSendJob(mediaPacket);
                queue.addJob (mediaSendJob);
                Utility.debug("Picture job requested", imagePath);
            }
        }
    };
}
